<html>
  <head>
    <title>DOM的Diffing算法</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/javascript" src="../../js/react_v18.2.0/react.development.js"></script>
    <script type="text/javascript" src="../../js/react_v18.2.0/react-dom.development.js"></script>
    <script type="text/javascript" src="../../js/babel.min.js"></script>
    <script type="text/babel">
      class DateCom extends React.Component {
        state = {
          date: new Date(),
        }

        __interval__ = null

        componentDidMount() {
          this.__interval__ = setInterval(() => {
            this.setState({ date: new Date() });
          }, 1000);
        }

        componentWillUnmount() {
          clearInterval(this.__interval__);
        }

        render() {
          return (
            <div>
              <h1>Hello Judith</h1>
              <input type="text" /> <br />
              <div>
                当前时间是: {this.state.date.toTimeString()}
              </div>
            </div>
          );
        }
      }

      class Person extends React.Component {
        state = {
          persons: [
            { id: 1, name: 'Judith', age: 19 },
            { id: 2, name: "Jane", age: 18 },
          ],
        }

        add = () => {
          const { persons } = this.state;
          this.setState({
            persons: [
              { id: persons.length + 1, name: '张三', age: 21 },
              ...persons
            ],
          });
        }

        render() {
          return (
            <div>
              <button onClick={this.add}>添加一个张三</button>
              <h2>使用id作为key</h2>
              <ul>
                {this.state.persons.map(p => <li key={p.id}>姓名: {p.name}  年龄：{p.age} <input type="text" /> </li>)}
              </ul>
              <hr />
              <h2>使用index作为key</h2>
              <ul>
                {this.state.persons.map((p, index) => <li key={index}>姓名: {p.name}  年龄：{p.age} <input type="text" /> </li>)}
              </ul>
            </div>
          );
        }
      }

      ReactDOM.render(<Person />, document.getElementById('root'));
    </script>
  </body>
</html>
